$(function(){
	$('.cfmOrder_heard img').bind('click',function(){
		window.location.href = document.referrer; //返回上一页并刷新
	});
	var obj = {
		goodId : 0,						//商品id
		adressId : 0,					//收货地址ID
		skuId:null,						//skuid
		name : $('.Name'),				//姓名
		tel : $('.telephone'),			//联系方式
		Province : $('.province'),		//省
		City : $('.city'),				//市
		Area : $('.area'),				//区
		goodName : $('.goodName'),		//商品名称
		goodAttr : $('.goodAttr'),		//已选商品属性
		goodPrice : $('.goodPrice'),	//商品价格
		goodNum : $('.goodNum'),		//商品数量
		botNum : $('.botNum'),			//底部的数量
		botMoney : $('.botMoney'),		//底部的总金额
		payMoney : $('.payMoney'),		//支付窗口的价格
		num : $('.num.float'),			//商品加减处的数量
		pic : $('.smallPic')			//缩略图
	}
	
	loadPage();     //进入页面加载地址
	function loadPage(){
		showGoodInfo();		//进入页面立即执行，加载商品信息
		if(localStorage.getItem('data')){	//如果有编辑地址也的缓存地址加载缓存地址，首次进入页面加载地址页的默认地址
			var adressData = JSON.parse(localStorage.getItem('data'));
			obj.name.text(adressData.name);
			obj.tel.text(adressData.tel);
			obj.Province.text(adressData.sheng);
			obj.City.text(adressData.shi);
			obj.Area.text(adressData.qu);
			obj.adressId = adressData.id;
			confirmPay();	//如果地址存在才可以使用下单功能
		}else{
			promptlyLoad();
			confirmPay();	//如果地址存在才可以使用下单功能
		}
	}
	
	//加载地址信息
	function promptlyLoad(){
		$.ajax({
			type:"post",
			url:"http://a.91jfk.com/Product/Address/address_default",
			dataType:'json',
			success:function(res){
				console.log(res);
				if(res.code == '1'){
					var data = res.msg;
					obj.adressId = data.id;
					obj.name.text(data.name);
					obj.tel.text(data.tel);
					obj.Province.text(data.area);
					obj.City.text(data.street);
					obj.Area.text(data.address);
				} else {
					$(".errAlert").text("请添加地址...").addClass("AlertShow");
					setTimeout(function() {
						$(".errAlert").removeClass("AlertShow");
					}, 3000);
				}
			},
			error:function(err){
				console.log(err)
			}
		});
	}
	
	function showGoodInfo(){
		obj.goodId = localStorage.getItem('JFSCid');
		obj.skuId = localStorage.getItem('skuId');
		obj.goodName.text(localStorage.getItem('JFSCname'));
		obj.goodPrice.text(localStorage.getItem('JFSCprice'));
		obj.goodNum.text(localStorage.getItem('JFSCnum'));
		obj.num.val(localStorage.getItem('JFSCnum'));
		obj.goodAttr.text(localStorage.getItem('JFSCyixuan').replace(/'/g,''));
		obj.pic[0].src = localStorage.getItem('JFSCpic');
		obj.botNum.text(localStorage.getItem('JFSCnum'));
		var total = ((localStorage.getItem('JFSCnum')) * (localStorage.getItem('JFSCprice'))).toFixed(2);
		obj.botMoney.text(total);
	}
	
	//商品数量加减
    //数量加按钮  
    $(".buy_num .add").click(function(){  
        obj.num.val(parseInt(obj.num.val()) + 1);
        obj.botNum.text(parseInt(obj.botNum.text()) + 1);
        obj.goodNum.text(parseInt(obj.goodNum.text()) + 1);
        var countTotal = (obj.goodNum.text() * (localStorage.getItem('JFSCprice'))).toFixed(2);
        obj.botMoney.text(countTotal);
        $(".buy_num .reduce").removeAttr("disabled");           //当按加1时，设置$(".buy_num .reduce")为可点击状态
    });
    //数量减按钮  
    $(".buy_num .reduce").click(function(){  
        if (parseInt(obj.num.val()) > 1) {                 		 	//判断数量值大于1时才可以减少  
        	obj.num.val(parseInt(obj.num.val()) - 1);
        	obj.botNum.text(parseInt(obj.botNum.text()) - 1);
        	obj.goodNum.text(parseInt(obj.goodNum.text()) - 1);
        	var countTotal = (obj.goodNum.text() * (localStorage.getItem('JFSCprice'))).toFixed(2);
        	obj.botMoney.text(countTotal);
        }else{  
        	$(".buy_num .reduce").attr("disabled",true);  		//当num为1时，设置$(".buy_num .reduce")为不可点击状态
        	$(".errAlert").text("商品数量至少为一件").addClass("AlertShow");
        	setTimeout(function(){
	        	$(".errAlert").removeClass("AlertShow");
	        },3000);  
       	} 
    });
    
	//点击顶部跳转地址页面
	$('.address').bind('click',function(){
		window.location.href = 'point_shop_guanlidizhi.html';
	});
	
    //点击滑动开关
    $('.switch').bind('click',function(){
    	if($('.switch').is(':checked')){
    		console.log('我是滑动开关，我被点击了...');
	 	}
    });
    
    //点击确认下单按钮
    function confirmPay(){
    	$('.cfmOrder_cfm').bind('click',function(){
	    	$('.cfmOrder_foot').css('display','none');
	    	$('.payment_foot').css('display','block');
	    	$('.mask').css('display','block');
	    	var amount = $('.num.float').val();
	    	var payMoney = (amount * localStorage.getItem('JFSCprice')).toFixed(2);
	    	obj.payMoney.text(payMoney);
	    	if (payMoney == obj.botMoney.text()) {
				//点击圆圈选择支付方式
			    var payWay;		//用于记录支付方式
			    $('.mode_row').bind('click',function(){
			    	$(this).children('.row_Rt').find('.pur').addClass('addCir');
			    	$(this).siblings().children('.row_Rt').find('.pur').removeClass('addCir');
			    	var a = $(this).children('input[type=hidden]').val();
			    	//payWay = $(this).children('.row_con').find('.mode_name').text();
			    	payWay = a;
			    	console.log(payWay,obj.goodId,amount,obj.adressId,obj.skuId);
			    	//点击确认支付
			    	$('.confirm_cfm').unbind('click').click(function(){
				    	$.ajax({
				    		type:"post",
				    		url:"http://a.91jfk.com/Product/Nowbuy/create_order",
				    		data:{
				    			id:obj.goodId,
				    			sku_combination:obj.skuId,
				    			num:amount,
				    			address_id:obj.adressId
				    		},
				    		dataType:'json',
				    		success:function(res){
				    			console.log(res);
				    			if (res.code == 1) {
				    				if(payWay == '1'){
							    		console.log('微信支付');
							    		console.log(res.orderid);
							    		$.ajax({
											url: "http://a.91jfk.com/Product/WxJsAPI/jsApiCall",
											type: "post",
											data: {
												orderId: res.orderid
											},
											datatype: "json",
											success: function(xhr) {
												console.log(xhr);
												var data = JSON.parse(xhr);
												callpay(data.jsApiParameters);
											},
											error: function(err) {
												console.log(err);
												console.log('支付失败');
											}
										});//ajax结束
							    	}else if(payWay == '2'){
							    		console.log('连连支付');
							    		//location.href = "../Lianlianpay/send/no_order/" + order; //连连接口
							    	}else{
							    		console.log('请选择付款方式...');
							    		$(".errAlert").text("请选择付款方式...").addClass("AlertShow");
							        	setTimeout(function(){
								        	$(".errAlert").removeClass("AlertShow");
								        },3000);
							    	}
				    			}else{
				    				$(".errAlert").text(res.msg).addClass("AlertShow");
						        	setTimeout(function(){
							        	$(".errAlert").removeClass("AlertShow");
							        },3000);
				    			}
				    		},
				    		error:function(err){
				    			console.log(err);
				    		}
				    	});
				    });
			    });
	    	}
	    });
    }
    
    //调用微信支付接口
    function callpay(arg) {
		if(typeof WeixinJSBridge == "undefined") {
			if(document.addEventListener) {
				document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
			} else if(document.attachEvent) {
				document.attachEvent('WeixinJSBridgeReady', jsApiCall);
				document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
			}
		} else {
			jsApiCall(arg);
		}
	}

	//调用微信JS api 支付
	function jsApiCall(arg) {
		var data = JSON.parse(arg);
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest',
			data,
			function(res) {
				WeixinJSBridge.log(res.err_msg);
				if(res.err_msg == "get_brand_wcpay_request:ok") {
					//alert("支付成功");
				} else if(res.err_msg == "get_brand_wcpay_request:cancel") {
					//alert("取消支付");
				} else {
					//alert(res.err_msg);
					//alert("支付失败");
				}
			});
	}
    
    //点击关闭按钮
    $('.close').bind('click',function(){
    	$('.cfmOrder_foot').css('display','block');
    	$('.payment_foot').css('display','none');
    	$('.mask').css('display','none');
    });
});
